package com.tdcoding.chat.server;

import java.security.cert.CertificateException;

import javax.net.ssl.SSLException;

import com.tdcoding.chat.constants.ChatConstants;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateHandler;

public class ChatInitializer extends ChannelInitializer<SocketChannel> {
	private SslContext sslContext;

	public ChatInitializer() throws CertificateException, SSLException {
//		SelfSignedCertificate ssc = new SelfSignedCertificate();	
//		sslContext = SslContext.newServerContext(ssc.certificate(),ssc.privateKey(),"123456");
	}

	@Override
	public void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();

		if (ChatConstants.NEED_SSL) {
			// if (sslContext != null) {
			// SSLEngine engine = sslContext.newEngine(ch.alloc());
			// engine.setUseClientMode(false);
			// engine.setNeedClientAuth(true);
			// pipeline.addLast(new SslHandler(engine));
			// }
		}

		pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
		pipeline.addLast(new LengthFieldPrepender(4));
//		pipeline.addLast(new StringDecoder());
//		pipeline.addLast(new StringEncoder());
		
		
		pipeline.addLast(new ByteArrayDecoder());
		pipeline.addLast(new ByteArrayEncoder());

//		pipeline.addLast(new ProtostuffDecoder());
//		pipeline.addLast(new ChatDecoder(ResponseInfo.class)); 
//		pipeline.addLast(new ProtostuffPrepender());
//		pipeline.addLast(new ChatEncoder(RequestInfo.class)); 
//		
		pipeline.addLast("heartbeat", new IdleStateHandler(30,0,15));
		pipeline.addLast("chatHandler", new ChatHandler());
	}
}
